#!/bin/bash
# Install ROS on NVIDIA Jetson Developer Kits
# Copyright (c) JetsonHacks, 2019-2021


# Setup sources.lst
sudo sh -c '. /etc/lsb-release && echo "deb http://mirrors.tuna.tsinghua.edu.cn/ros/ubuntu/ `lsb_release -cs` main" > /etc/apt/sources.list.d/ros-latest.list'
# Setup keys
sudo apt install curl 
curl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -

sudo apt update

echo "Installing ROS"

# This is where you might start to modify the packages being installed, i.e.
sudo apt-get install ros-melodic-desktop-full

# Here we loop through any packages passed on the command line
# Install packages ...


# Add Individual Packages here
# You can install a specific ROS package (replace underscores with dashes of the package name):
# sudo apt-get install ros-melodic-PACKAGE
# e.g.
# sudo apt-get install ros-melodic-navigation
#
# To find available packages:
# apt-cache search ros-melodic
# 
# Initialize rosdep
tput setaf 2
echo "Installing rosdep"
tput sgr0
sudo apt-get install python-rosdep -y
# Initialize rosdep
tput setaf 2
echo "Initializaing rosdep"
tput sgr0
sudo rosdep init
# To find available packages, use:
rosdep update
# Environment Setup - source melodic setup.bash
# Don't add /opt/ros/melodic/setup.bash if it's already in bashrc
grep -q -F 'source /opt/ros/melodic/setup.bash' ~/.bashrc || echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
source ~/.bashrc
# Install rosinstall
tput setaf 2
echo "Installing rosinstall tools"
tput sgr0

# Install useful ROS dev tools
sudo apt-get install -y python-rosinstall \
  python-rosinstall-generator \
  python-wstool \
  build-essential

# Use ip to get the current IP addresses of eth0 and wlan0; parse into form xx.xx.xx.xx
ETH0_IPADDRESS=$(ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1)
WLAN_IPADDRESS=$(ip -4 -o addr show wlan0 | awk '{print $4}' | cut -d "/" -f 1)

if [ -z "$ETH0_IPADDRESS" ] ; then
  echo "Ethernet (eth0) is not available"
else
  echo "Ethernet (eth0) is $ETH0_IPADDRESS"
fi
if [ -z "$WLAN_IPADDRESS" ] ; then
  echo "Wireless (wlan0) is not available"
else
  echo "Wireless (wlan0) ip address is $WLAN_IPADDRESS"
fi

# Default to eth0 if available; wlan0 next
ROS_IP_ADDRESS=""
if [ ! -z "$ETH0_IPADDRESS" ] ; then
  ROS_IP_ADDRESS=$ETH0_IPADDRESS
else
  ROS_IP_ADDRESS=$WLAN_IPADDRESS
fi
if [ ! -z "$ROS_IP_ADDRESS" ] ; then
  echo "Setting ROS_IP in ${HOME}/.bashrc to: $ROS_IP_ADDRESS"
else
  echo "Setting ROS_IP to empty. Please change ROS_IP in the ${HOME}/.bashrc file"
fi

#setup ROS environment variables
grep -q -F ' ROS_MASTER_URI' ~/.bashrc ||  echo 'export ROS_MASTER_URI=http://localhost:11311' | tee -a ~/.bashrc
grep -q -F ' ROS_IP' ~/.bashrc ||  echo "export ROS_IP=${ROS_IP_ADDRESS}" | tee -a ~/.bashrc
tput setaf 2

echo "Installation complete!"
echo "Please setup your Catkin Workspace"
tput sgr0

